import requests
import re
import time

def get_first_parts_from_A_arrays_v2_optimized():
    """
    优化版本：获取所有A数组中指定位置的内容
    
    Returns:
        list: 包含解析后数据的列表，每个元素为包含[first_part, fifth_sixth_part, eighth_ninth_part]的列表
    """
    # 生成URL
    timestamp = int(time.time())
    r = str(timestamp)+"000"
    url = f'https://live.nowscore.com/data/bf.js?{r}'
    print("访问链接:"+url)
    
    # 请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.562.400 QQBrowser/19.6.6725.400',
        'Referer': 'https://live.nowscore.com/2in1.aspx'
    }
    
    # 发送请求，设置超时时间
    response = requests.get(url, headers=headers, timeout=10)
    # 直接使用UTF-8编码，避免检测编码的开销（根据网站实际情况调整）
    response.encoding = 'utf-8'
    content = response.text
    
    # print(content)
    # 使用编译的正则表达式提高匹配效率
    pattern = re.compile(r'A\[\d+\]\s*=\s*\[([^\]]*)\]')
    matches = pattern.findall(content)
    
    # 预分配结果列表大小（如果可以预估）
    result_parts = []
    
    # 优化的解析逻辑
    for string_content in matches:
        # 按^分割内容，但只分割到我们需要的索引位置，避免完全分割
        parts = string_content.split(',')
        
        # 获取所需部分，确保索引存在
        first_part = parts[0] if len(parts) > 0 else ""

        # 处理第五部分，去除HTML标签和引号
        fifth_sixth_part = parts[4] if len(parts) > 4 else ""
        if fifth_sixth_part:
            # 去除首尾的单引号或双引号
            fifth_sixth_part = fifth_sixth_part.strip()
            if (fifth_sixth_part.startswith("'") and fifth_sixth_part.endswith("'")) or \
            (fifth_sixth_part.startswith('"') and fifth_sixth_part.endswith('"')):
                fifth_sixth_part = fifth_sixth_part[1:-1]
            # 去除HTML标签
            fifth_sixth_part = re.sub(r'<[^>]+>', '', fifth_sixth_part).strip()

        eighth_ninth_part = parts[7] if len(parts) > 7 else ""
        if eighth_ninth_part:
            # 去除首尾的单引号或双引号
            eighth_ninth_part = eighth_ninth_part.strip()
            if (eighth_ninth_part.startswith("'") and eighth_ninth_part.endswith("'")) or \
            (eighth_ninth_part.startswith('"') and eighth_ninth_part.endswith('"')):
                eighth_ninth_part = eighth_ninth_part[1:-1]
            # 去除HTML标签
            eighth_ninth_part = re.sub(r'<[^>]+>', '', eighth_ninth_part).strip()

        result_parts.append([first_part, fifth_sixth_part, eighth_ninth_part])
    
    return result_parts

# 使用示例
if __name__ == "__main__":
    print("开始提取数据...")
    

    # 测试优化版本
    start_time = time.time()
    result_list_optimized = get_first_parts_from_A_arrays_v2_optimized()
    end_time = time.time()
    execution_time_optimized = end_time - start_time
    
    print("优化版本结果:")
    for result in result_list_optimized:
        print(result)

    print(f"优化版本运行时间: {execution_time_optimized:.4f} 秒")
    print(f"优化版本结果数量: {len(result_list_optimized)}")